package niuke;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * @author lj
 * @Description: 分别按照二叉树先序，中序和后序打印所有的节点。
 * @date 2020-10-30 14:05
 * @QQ 851477108
 */


public class erchashupaixu {
    public static class TreeNode{
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        TreeNode(int x){
            val = x;
        }
    }

    public int[][] threeOrders(TreeNode root){
        if (root == null)return null;
        //首先遍历
        preOrder(root);
        inOrder(root);
        postOder(root);

        //记录遍历结果的长度，三种遍历长度相等，任取一种即可
        int len = pre.size();
        //结果数组
        int[][] res = new int[3][len];
        //遍历ArrayList，存入数组中
        for (int i = 0; i < len; i++) {
            res[0][i] = pre.get(i);
        }

        for (int i = 0; i < len; i++) {
            res[1][i] = in.get(i);
        }

        for (int i = 0; i < len; i++) {
            res[2][i] = post.get(i);
        }

        return res;
    }

    //建三个ArrayList分别存储三种遍历的结果
    ArrayList<Integer> pre = new ArrayList<>();
    ArrayList<Integer> in = new ArrayList<>();
    ArrayList<Integer> post = new ArrayList<>();

    //前序遍历
    public void preOrder(TreeNode root){
        if (root != null){
            pre.add(root.val);
            preOrder(root.left);
            preOrder(root.right);
        }
    }

    //中序遍历
    public void inOrder(TreeNode root){
        if (root != null){
            inOrder(root.left);
            in.add(root.val);
            inOrder(root.right);
        }
    }

    //后序遍历
    public void postOder(TreeNode root){
        if (root != null){
            postOder(root.left);
            postOder(root.right);
            post.add(root.val);
        }
    }
}
